<?php
/**
 * 分销关系模型
 * 用于记录用户之间的分销关系
 */

namespace app\model;

use think\Model;

class DistributionRelationModel extends Model
{
    // 设置表名
    protected $name = 'sh_distribution_relation';
    
    // 设置主键
    protected $pk = 'id';
    
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    /**
     * 建立分销关系
     * @param int $customer_id 客户ID
     * @param int $distributor_id 分销员ID
     * @param int $level 分销层级
     */
    public static function createRelation($customer_id, $distributor_id, $level = 1)
    {
        // 检查是否已存在关系
        $exists = self::where([
            'customer_id' => $customer_id,
            'distributor_id' => $distributor_id
        ])->find();
        
        if ($exists) {
            return $exists;
        }
        
        // 创建新关系
        $data = [
            'customer_id' => $customer_id,
            'distributor_id' => $distributor_id,
            'level' => $level,
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        return self::create($data);
    }
    
    /**
     * 获取用户的上级分销员
     * @param int $customer_id 客户ID
     * @param int $level 层级（1-一级分销员，2-二级分销员）
     */
    public static function getDistributor($customer_id, $level = 1)
    {
        return self::alias('dr')
            ->join('sh_distribution_distributor dd', 'dr.distributor_id = dd.customer_id')
            ->join('customer c', 'dd.customer_id = c.id')
            ->field('dd.*, c.name as customer_name, c.telephone, c.avatar')
            ->where([
                'dr.customer_id' => $customer_id,
                'dr.level' => $level,
                'dd.status' => 1 // 确保分销员是启用状态
            ])
            ->find();
    }
    
    /**
     * 获取分销员的下级客户
     * @param int $distributor_id 分销员ID
     * @param int $level 层级
     */
    public static function getCustomers($distributor_id, $level = 1)
    {
        return self::alias('dr')
            ->join('customer c', 'dr.customer_id = c.id')
            ->field('dr.*, c.name as customer_name, c.telephone, c.avatar')
            ->where([
                'dr.distributor_id' => $distributor_id,
                'dr.level' => $level
            ])
            ->select();
    }
    
    /**
     * 删除分销关系
     */
    public static function deleteRelation($id)
    {
        return self::where(['id' => $id])->delete();
    }
}